package com.jsbs.iam.component.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jsbs.iam.component.dto.CusSerializer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

public class Json {
    private static Gson gson;
    static{
        gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new CusSerializer.LocalDateSerializer())
                .registerTypeAdapter(LocalDate.class, new CusSerializer.LocalDateDeserializer())
                .registerTypeAdapter(LocalDateTime.class, new CusSerializer.LocalDateTimeSerializer())
                .registerTypeAdapter(LocalDateTime.class, new CusSerializer.LocalDateTimeDeserializer())
                .disableHtmlEscaping().create();
    }
    public static String toJsonString(Object o){
        return gson.toJson(o);
    }

    public static <T> T parseJson(String json, Class<T> clazz){
        return gson.fromJson(json, clazz);
    }

    public static <T> T parseJson(String json, Type type){
        return gson.fromJson(json, type);
    }

    //参考：https://www.jianshu.com/p/701ae370f959
    public static <T> List<T> parseJsonArray(String json, Class<T> clazz){
        Type type = new ParameterizedTypeImpl(clazz);
        List<T> list =  gson.fromJson(json, type);
        return list;
    }

    private static class ParameterizedTypeImpl implements ParameterizedType {
        Class clazz;

        public ParameterizedTypeImpl(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }
}
